package org.dromara.genealogy.controller;

import java.util.Arrays;
import java.util.List;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.tree.Tree;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.core.utils.file.MimeTypeUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.helper.DataPermissionHelper;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.genealogy.domain.bo.GeDirectoryBo;
import org.dromara.genealogy.domain.vo.GeNameTranVo;
import org.dromara.genealogy.domain.vo.NameTreeVo;
import org.dromara.system.controller.system.SysProfileController;
import org.dromara.system.domain.vo.SysOssVo;
import org.dromara.system.service.ISysOssService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.genealogy.domain.vo.GeNameVo;
import org.dromara.genealogy.domain.bo.GeNameBo;
import org.dromara.genealogy.service.IGeNameService;
import org.springframework.web.multipart.MultipartFile;

/**
 * 世代名称
 *
 * @author qianjm
 * @date 2025-09-04
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/genealogy/name")
public class GeNameController extends BaseController {

    private final IGeNameService geNameService;

    private final ISysOssService ossService;

    /**
     * 查询世代名称列表
     */
    @SaCheckPermission("genealogy:name:list")
    @GetMapping("/list")
    public R<Page<GeNameVo>> list(GeNameBo bo, PageQuery pageQuery) {
        return R.ok(geNameService.selectPageNameList(bo, pageQuery));
    }

    /**
     * 导出世代名称列表
     */
    @SaCheckPermission("genealogy:name:export")
    @Log(title = "世代名称", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(GeNameBo bo, HttpServletResponse response) {
        List<GeNameVo> list = geNameService.queryList(bo);
        ExcelUtil.exportExcel(list, "世代名称", GeNameVo.class, response);
    }

    /**
     * 获取世代名称详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("genealogy:name:query")
    @GetMapping("/{id}")
    public R<GeNameVo> getInfo(@NotNull(message = "主键不能为空") @PathVariable Long id) {
        return R.ok(geNameService.queryById(id));
    }

    /**
     * 获取族员详细信息(字段翻译之后)
     *
     * @param id 主键
     */
    @SaCheckPermission("genealogy:name:query")
    @GetMapping("/trans/{id}")
    public R<GeNameTranVo> getInfoTrans(@NotNull(message = "主键不能为空") @PathVariable Long id) {
        return R.ok(geNameService.queryTransById(id));
    }

    /**
     * 新增世代名称
     */
    @SaCheckPermission("genealogy:name:add")
    @Log(title = "世代名称", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody GeNameBo bo) {
        return toAjax(geNameService.insertByBo(bo));
    }

    /**
     * 修改世代名称
     */
    @SaCheckPermission("genealogy:name:edit")
    @Log(title = "世代名称", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody GeNameBo bo) {
        return toAjax(geNameService.updateByBo(bo));
    }

    /**
     * 删除世代名称
     *
     * @param ids 主键串
     */
    @SaCheckPermission("genealogy:name:remove")
    @Log(title = "世代名称", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(geNameService.deleteWithValidByIds(List.of(ids), true));
    }

    /**
     * 获取族员树列表
     */
    @SaCheckPermission("genealogy:name:query")
    @PostMapping("/genealogyNameTree")
    public R<List<Tree<Long>>> genealogyNameTree(GeNameBo bo) {
        return R.ok(geNameService.genealogyNameTreeList(bo));
    }

    /**
     * family tree获取族员树列表
     */
    @SaIgnore
    @SaCheckPermission("genealogy:name:query")
    @PostMapping("/nameTreeList")
    public R<NameTreeVo> nameTree(GeNameBo bo) {
        return R.ok(geNameService.nameTreeList(bo));
    }

    /**
     * 头像上传
     *
     * @param avatarfile 用户头像
     */
    @RepeatSubmit
    @Log(title = "族员头像", businessType = BusinessType.UPDATE)
    @SaIgnore
    @PostMapping(value = "/avatar", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<GeNameController.AvatarVo> avatar(@RequestPart("file") MultipartFile avatarfile) {
        if (!avatarfile.isEmpty()) {
            String extension = FileUtil.extName(avatarfile.getOriginalFilename());
            if (!StringUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.IMAGE_EXTENSION)) {
                return R.fail("文件格式不正确，请上传" + Arrays.toString(MimeTypeUtils.IMAGE_EXTENSION) + "格式");
            }
            SysOssVo oss = ossService.upload(avatarfile);
            String avatar = oss.getUrl();
            /*boolean updateSuccess = DataPermissionHelper.ignore(() -> geNameService.updateAvatar(LoginHelper.getUserId(), oss.getOssId()));
            if (updateSuccess) {
                return R.ok(new SysProfileController.AvatarVo(avatar));
            }*/
            return R.ok(new GeNameController.AvatarVo(avatar,oss.getOssId()));
        }
        return R.fail("上传图片异常，请联系管理员");
    }

    public record AvatarVo(String imgUrl,Long ossId) {}
}
